let _Vue = null;

// 自定义 vuex 插件 每次触发 cart 中的 mutations 的时候 会重新存入本地
const myPlugin = store => {
  store.subscribe((mutation, state) => {
    console.log(mutation)
    if (mutation.type.startsWith('cart/')) {
      window.localStorage.setItem('cart-products', JSON.stringify(state.cart.cartProducts))
    }
  })
}

class Store {
  constructor(options) {
    const { store = {},
      getters = {},
      mutations = {},
      actions = {}
    } = options;
    // 使用 Vue 原型提供的 observable 方法将 state 中的属性变成响应式的
    this.state = _Vue.observable(state);

    // 遍历 getters 将 getters 变成 get 的形式存入 this.getters 中
    // 并且在调用的时候传入 state
    this.getters = Object.create(null);
    Object.keys(getters).forEach(key => {
      Object.defineProperties(this.getters, key, {
        get: () => this.getters[key](this.state)
      });
    });

    this._mutations = mutations;
    this._actions = actions;
  }

  commit(type, payload) {
    this._mutations[type](payload);
  }

  dispatch(type, payload) {
    this._actions[type](payload);
  }
}

function install(Vue) {
  _Vue = Vue;
  _Vue.mixin({
    beforeCreate() {
      if (this.$options.store) {
        _Vue.prototype.$store = this.$options.store;
      }
    }
  })
}

export default {
  Store,
  install
}